import { defineStore } from 'pinia';
import { store } from '@/store';
import { ACCESS_TOKEN, CURRENT_USER, IS_LOCKSCREEN } from '@/store/mutation-types';
import { has } from 'lodash-es';
import { createStorage, storage } from '@/utils/Storage';
import { RoleEnum } from '@/enums/roleEnum';
import {PERMISSION_KEY, ROLES_KEY, TOKEN_KEY, USER_INFO_KEY} from '@/enums/cacheEnum';
import { setAuthCache, getAuthCache } from '@/utils/auth';
import { ErrorMessageMode } from '/#/index';
import {doLogout, getPermCode, getUserInfo, loginApi} from '@/api/user';
import { PageEnum } from '@/enums/pageEnum';
import { isArray } from '@/utils/is';
import router from "@/router/index"
export interface IUserState {
	token: string;
	username: string;
	welcome: string;
	avatar: string;
	lastUpdateTime: number;
	roleList: any[];
	permission: any[];
	userInfo: any;
	sessionTimeout?: boolean;
}
export interface LoginParams {
  account: string;
  password: string;
}
const sStorage = createStorage({ storage: sessionStorage });

export const useUserStore = defineStore({
	id: 'app-user',
	state: (): IUserState => ({
		token: getAuthCache<string>(TOKEN_KEY),
		username: '',
		welcome: '',
		lastUpdateTime: 0,
		avatar: '',
		roleList: [],
		permission: [],
		userInfo: getAuthCache<any>(USER_INFO_KEY),
		sessionTimeout: false,
	}),
	getters: {
		getToken(): string {
			return this.token || getAuthCache<string>(TOKEN_KEY);
		},
		getAvatar(): string {
			console.log(this.userInfo);
			console.log(has(this.userInfo, 'avatar'));
			return has(this.userInfo, 'avatar') ? this.userInfo.avatar : '';
		},
		getUserName(): string {
			return this.userInfo.realName;
		},
		getUserInfo(): object {
			console.log(this.userInfo);
			return this.userInfo || getAuthCache<any>(USER_INFO_KEY) || {};
		},
		getPermissions():Array<any>{
			return this.permission.length > 0 ? this.permission : getAuthCache(PERMISSION_KEY);
		},
    getSessionTimeout(): boolean {
      return !!this.sessionTimeout;
    },
    getLastUpdateTime(): number {
      return this.lastUpdateTime;
    },
		getRoleList(): RoleEnum[] {
			return this.roleList.length > 0 ? this.roleList : getAuthCache<RoleEnum[]>(ROLES_KEY);
		},
	},
	actions: {
		setToken(token: string) {
			this.token = token ? token : '';
			setAuthCache(TOKEN_KEY, token);
		},
		setAvatar(avatar: string) {
			this.avatar = avatar;
		},
		setPermission(permission:string[]){
			this.permission = permission
			setAuthCache(PERMISSION_KEY, permission);
		},
    setSessionTimeout(flag: boolean) {
      this.sessionTimeout = flag;
    },
		setUserInfo(info) {
			this.userInfo = info;
			this.lastUpdateTime = new Date().getTime();
			setAuthCache(USER_INFO_KEY, info);
		},
		setRoleList(roleList: RoleEnum[]) {
			this.roleList = roleList;
			setAuthCache(ROLES_KEY, roleList);
		},
		async login(params: LoginParams & { goHome?: boolean; mode?: ErrorMessageMode }): Promise<any> {
			try {
				const { goHome = true, mode, ...loginParams } = params;
				const data = await loginApi(loginParams, mode);
				const { token } = data;

				// save token
				this.setToken(token);
				return this.afterLoginAction(goHome);
			} catch (error) {
				return Promise.reject(error);
			}
		},
		async afterLoginAction(goHome?: boolean): Promise<any> {
			if (!this.getToken) return null;
			const userInfo = await this.getUserInfoAction();

			const sessionTimeout = this.sessionTimeout;
 
			if (sessionTimeout) {
				this.setSessionTimeout(false);
			} else {
				goHome && (await router.replace(userInfo?.homePath || PageEnum.BASE_HOME));
			}
			return userInfo;
		},
		async getUserInfoAction(): Promise<any> {
			if (!this.getToken) return null;
			const userInfo = await getUserInfo();
			console.log(userInfo);
			const permissionCode =  await getPermCode()
			// 可改为后台实时获取
			if(isArray(permissionCode)){
				this.setPermission(permissionCode)
			}else{
				this.setPermission([])
			}
			const { roles = [] } = userInfo;
			if (isArray(roles)) {
				const roleList = roles.map((item) => item.value) as RoleEnum[];
				this.setRoleList(roleList);
			} else {
				userInfo.roles = [];
				this.setRoleList([]);
			}
			this.setUserInfo(userInfo);
			return userInfo;
		},
    async logout(goLogin = false) {
      if (this.getToken) {
        try {
          await doLogout();
        } catch {
          console.log('注销Token失败');
        }
      }
      this.setToken(undefined);
      this.setSessionTimeout(false);
      this.setUserInfo(null);
      goLogin && router.push(PageEnum.BASE_LOGIN);
    },
	},
});

export function useUserStoreWidthOut() {
	return useUserStore(store);
}
